package routes

import (
	"obsidian-plugin-server/config"
	"obsidian-plugin-server/controllers"
	"obsidian-plugin-server/middleware"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func SetupRoutes(router *gin.Engine, db *gorm.DB, cfg *config.Config) {
	// 模板
	router.LoadHTMLGlob("templates/*")

	// 静态资源：站点图标
	router.StaticFile("/favicon.svg", "./favicon.svg")

	// CORS
	router.Use(middleware.CORSMiddleware())

	// 控制器
	authController := &controllers.AuthController{
		DB:        db,
		JWTConfig: &cfg.JWT,
	}
	documentController := &controllers.DocumentController{
		DB: db,
	}
	tokenController := &controllers.TokenController{
		DB:        db,
		JWTConfig: &cfg.JWT,
	}
	webController := &controllers.WebController{
		DB: db,
	}

	// API 路由（对应 Laravel routes/api.php）
	api := router.Group("/api")
	{
		// 无需认证
		api.POST("/register", authController.Register)
		api.POST("/login", authController.Login)

		// 需要认证
		authorized := api.Group("")
		authorized.Use(middleware.AuthMiddleware(db, &cfg.JWT))
		{
			// 文档管理
			authorized.POST("/documents", documentController.Store)
			authorized.GET("/documents", documentController.Index)
			authorized.GET("/documents/:uuid", documentController.Show)
			authorized.PUT("/documents/:uuid", documentController.Update)
			authorized.DELETE("/documents/:uuid", documentController.Destroy)

			// Token 轮换
			authorized.POST("/token/rotate", tokenController.RotateToken)
		}
	}

	// Web 路由（对应 Laravel routes/web.php）
	// 文档查看
	router.GET("/d/:uuid", webController.ShowDocument)
	router.POST("/d/:uuid/verify", webController.VerifyDocumentPassword)

	// 文档下载
	router.GET("/d/:uuid/download", webController.DownloadDocument)

	// 文档列表（根据用户 UID，带搜索），等价于 Laravel /documents?uid=&search=
	router.GET("/documents", webController.DocumentListWithSearch)

	// 仪表盘
	router.GET("/dashboard", webController.Dashboard)

	// 首页
	router.GET("/", webController.Home)
}
